package cn.wolfcode.shop.member.service.impl;

import cn.wolfcode.shop.common.exception.BusinessException;
import cn.wolfcode.shop.common.util.CodeMsg;
import cn.wolfcode.shop.member.domain.User;
import cn.wolfcode.shop.member.mapper.UserMapper;
import cn.wolfcode.shop.member.service.ITokenService;
import cn.wolfcode.shop.member.vo.LoginVO;
import cn.wolfcode.shop.util.BaseKeyPrefix;
import cn.wolfcode.shop.redis.RedisService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class TokenServiceImpl implements ITokenService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public String login(LoginVO loginVO) {

        User user = userMapper.get(Long.parseLong(loginVO.mobile));

        if (user == null){
            throw new BusinessException(CodeMsg.LOGIN_ERROR);
        }

        String anObject = DigestUtils.md5Hex(loginVO.getPassword() + user.getSalt());
        System.out.println(anObject);
        if (!user.getPassword().equals(anObject)){
            throw new BusinessException(CodeMsg.PASSWORD_ERROR);
        }

        BaseKeyPrefix keyprefix = new BaseKeyPrefix(1800, "USER_TOKEN:");

        String key = UUID.randomUUID().toString().replace("-", "").substring(0, 6);

        redisService.set(keyprefix,key,user);

        return key;

    }

    @Override
    public User getCurrent(String token) {

        BaseKeyPrefix keyprefix = new BaseKeyPrefix(1800, "USER_TOKEN:");

        User user = redisService.get(keyprefix, token, User.class);

        return user;
    }

    @Override
    public List<User> list() {
        return userMapper.list();
    }
}
